package com.inspectortime.service.audit;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.inspectortime.common.PersistentEntityBase;
import com.inspectortime.domain.Inspection;
import com.inspectortime.domain.User;
import com.inspectortime.domain.impl.AuditEntryImpl;
import com.inspectortime.domain.type.AuditEntryType;

/**
 * TODO: Complete this service. We'll need something like this for launch. Is
 * currently not being called from anywhere.
 * 
 * @author mKvalsvik
 * 
 */
public class AuditService {

	protected static Log log = LogFactory.getLog(AuditService.class);

	public void login(User user, HttpServletRequest request) {
		AuditEntryImpl entry = new AuditEntryImpl();
		entry.setActorUserId((String) user.getId());
		entry.setType(AuditEntryType.Login);
		entry.setIpAddress(request.getRemoteAddr());
		entry.save();
	}

	private void logObjectEvent(User user, HttpServletRequest request,
			PersistentEntityBase targetObject, AuditEntryType type) {
		AuditEntryImpl entry = new AuditEntryImpl();
		entry.setActorUserId((String) user.getId());
		entry.setType(type);
		entry.setIpAddress(request.getRemoteAddr());
		entry.setTargetObjectId((String) targetObject.getId());
		entry.setTargetObjectClass(targetObject.getClass().getName());
		entry.save();

	}

	public void inspectionQuickScheduled(User user, HttpServletRequest request,
			Inspection inspection) {
		logObjectEvent(user, request, (PersistentEntityBase) inspection,
				AuditEntryType.InspectionQuickScheduled);
	}

	public void inspectionAutoExpired(User user, HttpServletRequest request,
			Inspection inspection) {
		logObjectEvent(user, request, (PersistentEntityBase) inspection,
				AuditEntryType.InspectionAutoExpired);
	}

	public void inspectionCompletelyScheduled(User user,
			HttpServletRequest request, Inspection inspection) {
		logObjectEvent(user, request, (PersistentEntityBase) inspection,
				AuditEntryType.InspectionCompletelyScheduled);
	}

	/**
	 * TODO: Perhaps implement some sort of aspect-oriented way of auditing
	 * object state changes. Perhaps associated with the
	 * PersistentEntityBase.save() method.
	 * 
	 * @param user
	 * @param request
	 * @param updatedObject
	 */
	public void update(User user, HttpServletRequest request,
			PersistentEntityBase updatedObject) {
		/*
		 * AuditEntryImpl entry = new AuditEntryImpl();
		 * entry.setActingUserId((String) user.getId());
		 * entry.setIpAddress(request.getRemoteAddr());
		 * entry.setType(AuditEntryType.Update);
		 * entry.setUpdatedObjectClass(updatedObject.getClass().getName());
		 * entry.setUpdatedObjectId((String) updatedObject.getId());
		 * 
		 * entry.save();
		 */
	}
}
